package com.surprise.base.util;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.collections.CollectionUtils;

import com.google.common.collect.Lists;

/**
 * ListUtils
 * @author nick
 * 2014年6月17日
 */
public class ListUtils {
    public static <T, K> List<T> convert(Collection<K> list, Class<T> clazz) {
        List<T> ret = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return ret;
        }

        Converter converter = BeanUtilsBean.getInstance().getConvertUtils()
                .lookup(clazz);
        if (converter == null) {
            return null;
        }
        for (K k : list) {
            T t = (T) converter.convert(clazz, k);
            ret.add(t);
        }
        return ret;
    }

    public static <T> List<T> toList(Collection<T> c) {
        if (c instanceof List) {
            return (List<T>) c;
        }
        List<T> list = Lists.newArrayList(c);
        return list;
    }
    
    public static <T> List<T> subList(List<T> list, int start, int end) {
        if (start >= end || start < 0) {
            return Collections.emptyList();
        }
        List<T> ret = Lists.newArrayList();
        for (int i = start; i < end && i < list.size(); i++) {
            ret.add(list.get(i));
        }
        return ret;
    }

    public static void main(String args[]) {
        List<Long> list = Lists.newArrayList(1L, 3L, 2L);
//        List<String> ret = convert(list, String.class);
//        System.out.println(ret);
        System.out.println(subList(list, 0, 3));
    }
}